<template>
  <div>
    <a-button @click="openModal" class="icon-selector-icon-wrapper">
      <span class="iconfont" v-html="iconValue"/>
    </a-button>

    <a-modal okText="确定" cancelText="取消" @ok="ok"
             width="800px" data-role="ignore-select-field" title="请选择图标" v-model="visible">
      <a-input-search style="margin-bottom: 5px" @search="search"/>
      <div class="icon-selector-container">
        <a-button @click="() => selected = icon.unicode"
                  class="icon-selector-icon-wrapper" v-for="icon in getPagedIcons">
          <span class="iconfont" v-html="`&#x${icon.unicode};`"></span>
        </a-button>
      </div>
      <div style="text-align: right; padding-top: 10px">
        <a-pagination size="small" show-quick-jumper :pageSize="pageSize"
                      :default-current="current" @change="pageChange"
                      :total="searchedIcons.length"/>
      </div>
    </a-modal>
  </div>
</template>
<script>
import {createModelForVue, createProps} from '@/utils';
import icons from '@/components/hhd/design/DesignTable/font/iconfont.json';

export default {
  name: 'IconSelector',
  model: createModelForVue('icon'),
  props: {
    icon: createProps(String),
  },
  data() {
    return {
      current: 1,
      icons: icons.glyphs,
      visible: false,
      pageSize: 120,
      selected: undefined,
      searchWord: undefined
    };
  },
  methods: {
    search(str) {
      this.current = 1;
      this.searchWord = str
    },
    ok() {
      if (this.selected) {
        this.$emit('change', this.selected);
      }
      this.close();
    },
    close() {
      this.visible = false;
    },
    openModal() {
      this.visible = true;
      this.current = 1;
      this.selected = undefined;
    },
    pageChange(current) {
      this.current = current;
    },
  },
  computed: {
    searchedIcons() {
      let list = this.icons;
      if (this.searchWord) {
        list = this.icons.filter(i => i.name.indexOf(this.searchWord) !== -1);
      }
      return list
    },
    getPagedIcons() {
      let res = [];
      let startIndex = (this.current - 1) * this.pageSize;
      let endIndex = startIndex + this.pageSize;
      while (startIndex < endIndex && startIndex < this.searchedIcons.length) {
        res.push(this.searchedIcons[startIndex++]);
      }
      return res;
    },
    iconValue() {
      if (this.icon) return `&#x${this.icon};`;
      return undefined;
    },
  }
};
</script>
<style>
.icon-selector-icon-wrapper {
  min-width: 30px;
  justify-content: center;
  align-items: center;
  display: flex;
  font-size: 22px;
}
.icon-selector-icon-wrapper .iconfont,
.icon-selector-container .iconfont {
  font-size: 22px;
}
.icon-selector-container {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-gap: 8px;
}
</style>